package com.qf.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.pojo.Student;
import com.qf.service.StudentService;
import com.qf.utils.Msg;
import com.qf.utils.Msg2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by luoxinmin on 2020/9/11.
 */
@Controller
@RequestMapping("/student")
public class StudentController {
    @Autowired
    private StudentService studentService;

    @RequestMapping(value = "/all", method = RequestMethod.GET)
    @ResponseBody
    public Msg2<Student> selectAll() {
        //page当前页
        //limt 每页行数
        //PageHeler.startPage(当前页，每页行数);----------测试
        //修改sql：select * from student limit ?,?----(page-1)*limit,limit
        //总行数：select counr(*) from student
        List<Student> list = studentService.selectAll();//null
        /*
            如果list为null,code=1,msg中设置“没有结果”
            如果list非null，code=0，才能读取data里的数据
         */
        Msg2<Student> msg = new Msg2<>();
        msg.setCode(0);
        msg.setData(list);
        //msg.setMsg("success");
        msg.setCount(list.size());//总数
        return msg;
    }

    @RequestMapping(value = "/all2/{page}", method = RequestMethod.GET)
    public ModelAndView selectAll2(ModelAndView mv, @PathVariable("page") int page) {
        PageHelper.startPage(page, 3);
        List<Student> list = studentService.selectAll();
        PageInfo<Student> pageInfo = new PageInfo<>(list);
        System.out.println(pageInfo);
        mv.addObject("slist", pageInfo);
        mv.setViewName("data");
        return mv;
    }

    @RequestMapping("/del/{id}")
    public String delete(@PathVariable("id") int id) {
        System.out.println("id===" + id);
        return "forward:/student/all2/1";
    }

    @RequestMapping("/one/{id}")
    @ResponseBody
    public Student selectOne(@PathVariable("id") int id) {
        Student student = studentService.selectOne(id);
        System.out.println(student);
        return student;
    }

    @RequestMapping("/update")
    @ResponseBody
    public Msg update(Student student) {
        System.out.println(student);
        Msg msg = new Msg();
        msg.setCode(1);
        return msg;
    }
}
